import { computed } from 'vue'

/**
 * 认证相关的组合式函数
 */
export function useAuth() {
  // 动态导入 store 避免循环依赖
  const getUserStore = () => {
    const { useUserStore } = require('@/stores/user')
    return useUserStore()
  }

  // 计算属性
  const isLoggedIn = computed(() => getUserStore().isLogin)
  const userInfo = computed(() => getUserStore().userInfo)
  const isAdmin = computed(() => getUserStore().isAdmin)
  const username = computed(() => getUserStore().username)

  // 检查登录状态
  const checkLoginStatus = () => {
    const token = uni.getStorageSync('token')
    if (!token) {
      redirectToLogin()
      return false
    }
    
    if (!userInfo.value) {
      getUserStore().checkLoginStatus()
    }
    return true
  }

  // 跳转到登录页
  const redirectToLogin = () => {
    uni.reLaunch({
      url: '/pages/login/login'
    })
  }

  // 跳转到首页
  const redirectToHome = () => {
    uni.reLaunch({
      url: '/pages/home/index'
    })
  }

  // 登录
  const login = async (credentials) => {
    try {
      getUserStore().login(credentials)
      return true
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 登出
  const logout = () => {
    return new Promise((resolve) => {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            getUserStore().logout()
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
    })
  }

  return {
    // 状态
    isLoggedIn,
    userInfo,
    isAdmin,
    username,
    // 方法
    checkLoginStatus,
    redirectToLogin,
    redirectToHome,
    login,
    logout
  }
}